import json
import os

class ConfigManager:
    def __init__(self, config_file):
        self.config_file = config_file
        self.default_config = {
            'last_port': 'COM18',
            'device_path': '/usb',
            'baudrate': 2000000,
            'local_path': os.path.expanduser(f'~\Desktop')
        }
        self.current_config = self.load()
        
    def load(self):
        """加载配置"""
        try:
            if os.path.exists(self.config_file):
                with open(self.config_file, 'r') as f:
                    return json.load(f)
        except Exception as e:
            print(f"加载配置文件失败: {e}")
        return self.default_config.copy()
        
    def save(self):
        """保存配置"""
        try:
            with open(self.config_file, 'w') as f:
                json.dump(self.current_config, f)
        except Exception as e:
            print(f"保存配置文件失败: {e}")
            
    def get(self, key, default=None):
        """获取配置项"""
        return self.current_config.get(key, default)
        
    def set(self, key, value):
        """设置配置项"""
        self.current_config[key] = value
        
    def update(self, config):
        """更新多个配置项"""
        self.current_config.update(config) 